package org.example;

import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class RedisPollingBackup {
    public static void main(String[] args) {
        Jedis jedisMain = new Jedis("127.0.0.1", 6379);
        Jedis jedisBackup = new Jedis("127.0.0.1", 6380);

        jedisMain.select(0);
        jedisBackup.select(1);

        while (true) {
            try {
                Thread.sleep(100); // 每隔100毫秒检查一次
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            // 获取主 Redis 中的所有键
            Set<String> mainKeys = jedisMain.keys("*");

            // 获取备份 Redis 中的所有键
            Set<String> backupKeys = jedisBackup.keys("*");

            // 需要备份的新增键
            List<String> keysToBackup = mainKeys.stream()
                    .filter(key -> !backupKeys.contains(key)) // 找到主 Redis 有而备份 Redis 没有的键
                    .collect(Collectors.toList());

            // 需要恢复的被删除键
            List<String> keysToRestore = backupKeys.stream()
                    .filter(key -> !mainKeys.contains(key)) // 找到备份 Redis 有而主 Redis 没有的键
                    .collect(Collectors.toList());

            // 备份新增的键到备份 Redis
            keysToBackup.forEach(key -> {
                String value = jedisMain.get(key);
                jedisBackup.set(key, value);
                System.out.println("Backed up key: " + key);
            });

            // 从备份 Redis 恢复被删除的键
            keysToRestore.forEach(key -> {
                String value = jedisBackup.get(key);
                jedisMain.set(key, value);
                System.out.println("Restored key: " + key);
            });
        }
    }
}
